package thread;

class MyBlockingQueue {
    int[] queue;//如何拿数组模拟实现队列呢?  循环数组--只有循环数组才能模拟实现队列
    int head = 0;
    int tail = 0;
    int size = 0;

    public MyBlockingQueue(int Capacity) {
        if (Capacity <= 0) {
            throw new RuntimeException("容量不能小于0");
        }
        queue = new int[Capacity];//初始化队列
    }

    private static Object locker = new Object();

    public void put(int value) {
        synchronized (locker) {
            while (size >= queue.length) {
                //阻塞等待
                try {
                    locker.wait();//等待唤醒
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            queue[tail] = value;
            //tail = (tail + 1) % queue.length;
            tail++;
            if (tail >= queue.length) {
                //越界了---归为到0
                tail = 0;
            }
            size++;//切记
            locker.notifyAll();
        }
    }

    public int take() {
        synchronized (locker) {
            while (size <= 0) {
                try {
                    locker.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            int value = queue[head];
            head++;
            if (head >= queue.length) {
                head = 0;
            }
            size--;
            locker.notifyAll();
            return value;
        }

    }

}

public class demo21 {

    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue(3);
        Thread t1 = new Thread(() -> {
            queue.put(1);
            System.out.println("放入1");
            queue.put(2);
            System.out.println("放入2");
            queue.put(3);
            System.out.println("放入3");
            queue.put(4);
            System.out.println("放入4");

        });
        Thread t2 = new Thread(() -> {
            try {
                Thread.sleep(1000);
                System.out.println("t2:" + queue.take());
                System.out.println("t2:" + queue.take());
                System.out.println("t2:" + queue.take());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        t1.start();
        t2.start();

    }


}
